package com.example.springboot.controller;


import com.example.springboot.common.Result;
import com.example.springboot.exception.FileUploadException;
import com.example.springboot.service.IPestImageService;
import com.example.springboot.utils.FileUtil;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/image")
public class PestImageController {

    @Autowired
    private IPestImageService pestImageService;

    @Autowired
    private FileUtil fileUtil;

    //上传图片并关联 pest
    @Transactional
    @PostMapping("/upload/{pestId}")
    public Result upload(@PathVariable Integer pestId,
                         @RequestPart("file") MultipartFile[] files) {

        List<String> imageNames = new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                fileUtil.upload(file);
                imageNames.add(file.getOriginalFilename());
            } catch (FileUploadException e) {
                log.error("上传文件 [{}] 失败", file.getOriginalFilename(), e);
            }
        }
        pestImageService.saveImages(pestId, imageNames);
        return Result.success(pestId);
    }

    /**
     * 获取 pest 图片url列表
     * @param pestId
     * @return
     */
    @GetMapping("/list/{pestId}")
    public Result listImageUrl(@PathVariable Integer pestId) {
        List<String> imageUrls = pestImageService.getByPestId(pestId);
        return Result.success(imageUrls);
    }

    /**
     * 删除单个 pest 图片
     * @param id
     * @return
     */
    @DeleteMapping("/image/delete/{id}")
    public Result deleteImage(@PathVariable Integer id) {
        pestImageService.deleteImage(id);
        return Result.success();
    }

    /**
     * 更新 pest 图片
     * @param pestId 虫害ID
     * @param files 新的图片文件
     * @return
     */
    /**
     * 更新 pest 图片
     * @param pestId 虫害ID
     * @param files 新的图片文件
     * @return
     */
    @PostMapping("/update/{pestId}")
    public Result updateImages(@PathVariable Integer pestId,
                               @RequestPart("file") MultipartFile[] files) {
        try {
            // 删除原有图片并上传新图片
            pestImageService.deleteByPestId(pestId);
            List<String> imageNames = uploadFiles(files);

            // 保存新图片信息到数据库
            pestImageService.saveImages(pestId, imageNames);
            return Result.success(pestId);
        } catch (Exception e) {
            log.error("更新图片失败，pestId: {}", pestId, e);
            return Result.error("图片更新失败");
        }
    }

    /**
     * 上传文件并返回文件名列表
     */
    @Transactional
    protected List<String> uploadFiles(MultipartFile[] files) {
        List<String> imageNames = new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                fileUtil.upload(file);
                imageNames.add(file.getOriginalFilename());
            } catch (FileUploadException e) {
                log.error("上传文件 [{}] 失败", file.getOriginalFilename(), e);
                throw e; // 抛出异常以便事务回滚
            }
        }
        return imageNames;
    }

}
